package com.xc.hotelmgr.webapi.modules.op.controller;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xc.hotelmgr.webapi.common.annotation.SysLog;
import com.xc.hotelmgr.webapi.modules.dt.entity.DtEntity;
import com.xc.hotelmgr.webapi.modules.dt.entity.StoreEntity;
import com.xc.hotelmgr.webapi.modules.dt.entity.StorePfEntity;
import com.xc.hotelmgr.webapi.modules.dt.service.DtService;
import com.xc.hotelmgr.webapi.modules.dt.service.StorePfService;
import com.xc.hotelmgr.webapi.modules.dt.service.StoreService;
import com.xc.hotelmgr.webapi.modules.ht.entity.HtBrandEntity;
import com.xc.hotelmgr.webapi.modules.ht.entity.HtCityinfoEntity;
import com.xc.hotelmgr.webapi.modules.ht.service.HtBrandService;
import com.xc.hotelmgr.webapi.modules.ht.service.HtCityinfoService;
import com.xc.hotelmgr.webapi.modules.ht.service.HtGroupService;
import com.xc.hotelmgr.webapi.modules.mq.service.HotelToMQService;
import com.xc.hotelmgr.webapi.modules.op.entity.*;
import com.xc.hotelmgr.webapi.modules.op.service.*;
import com.xc.hotelmgr.webapi.modules.sys.controller.AbstractController;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import com.xc.hotelmgr.webapi.common.utils.PageUtils;
import com.xc.hotelmgr.webapi.common.utils.R;



/**
 * 分组
 *
 * @author kemmy
 * @email kemmy@gmail.com
 * @date 2020-10-09 10:59:45
 */
@EnableAsync
@RestController
@RequestMapping("op/group")
@RequiredArgsConstructor
public class GroupController extends AbstractController {

    private final GroupService groupService;

    private final HtlGroupService htlGroupService;

    private final DtService dtService;

    private final StorePfService storePfService;

    private final StoreService storeService;

    private final HtCityinfoService htCityinfoService;

    private final HtBrandService htBrandService;

    private final DtUpHtlService dtUpHtlService;

    private final HotelToMQService hotelToMQService;

    private final HtGroupService htGroupService;


    /**
     * 根据storeId查询分组
     * @param storeId
     * @return
     */
    @RequestMapping(value = "/{storeId}", method = RequestMethod.GET)
    public R group(@PathVariable("storeId") Integer storeId) {
        List<GroupEntity> groupEntities = groupService.selectByStoreId(storeId);
        return R.ok().put("groupEntities", groupEntities);
    }

    @SysLog
    @RequestMapping("/dtpf")
    @RequiresPermissions("op:group:list")
    public R listDtPf(@RequestParam Map<String, Object> params){
        String inSql = "SELECT id FROM dt_dt WHERE FIND_IN_SET(id, getChild("+  getUserDtId()+ "))";
        List<DtEntity> dts =  dtService.getBaseMapper().selectList(new QueryWrapper<DtEntity>().inSql("id",inSql));
        List<StorePfEntity> spfs = storePfService.getBaseMapper().selectList(new QueryWrapper<StorePfEntity>());
        return R.ok().put("dts", dts).put("spfs",spfs);
    }

    /**
     * 查询机构下的店铺下拉列表
     */
    @SysLog
    @RequestMapping("/store")
    @RequiresPermissions("op:group:list")
    public R select(@RequestParam Map<String, Object> params){
        List<StoreEntity> list = storeService.queryByDtId(params);
        return R.ok().put("list", list);
    }

    /**
     * 查询城市信息下拉列表
     */
    @SysLog
    @RequestMapping("/citys")
    @RequiresPermissions("op:group:list")
    public R data(@RequestParam Map<String, Object> params){
        List<HtCityinfoEntity> list = htCityinfoService.queryData(params);
        return R.ok().put("list", list);
    }
    /**
     * 查询品牌列表
     */
    @SysLog
    @RequestMapping("/brand")
    @RequiresPermissions("op:group:list")
    public R listBrand(@RequestParam Map<String, Object> params){
        List<HtBrandEntity> list = htBrandService.getBaseMapper().selectList(new QueryWrapper<HtBrandEntity>());
        return R.ok().put("list", list);
    }

    /**
     * 列表
     */
    @SysLog
    @RequestMapping("/hotels")
    @RequiresPermissions("op:dtuphtl:list")
    public R listHotel(@RequestParam Map<String, Object> params){
        PageUtils page = dtUpHtlService.sqlQueryPageByName(params);
        return R.ok().put("page", page);
    }

    /**
     * 列表
     */
    @SysLog
    @RequestMapping("/group")
    @RequiresPermissions("op:group:list")
    public R listGroup(@RequestParam Map<String, Object> params) {
        String ownerDeptStr = getUserOwnerDept();
        String[] ownerDept = null;
        String dtId = (String) params.get("dtId");
        // 如果选择了机构，查询指定机构的数据
        if (!StringUtils.isEmpty(dtId) && !StringUtils.equals(dtId, getUserDtId().toString())) {
            ownerDept = new String[1];
            ownerDept[0] = dtId;
        } else {
            ownerDept = ownerDeptStr.split("\\,");
        }
        params.put("ownerDept", ownerDept);
        List<GroupEntity> list = groupService.sqlQuery(params);
        return R.ok().put("list", list);
    }

    @SysLog
    @RequestMapping("/groupps")
    @RequiresPermissions("op:group:listps")
    public R listGroupByPfStoreId(@RequestParam Map<String, Object> params) {
        String pfStr = (String) params.get("pf");
        String storeIdStr = (String) params.get("storeId");
        if(pfStr == null || storeIdStr == null) {
            return R.error("请选择平台和店铺");
        }
        Integer pf = Integer.valueOf(pfStr);
        Integer storeId = Integer.valueOf(storeIdStr);
        List<GroupEntity> list = groupService.getGrupByPfStoreId(pf, storeId);
        return R.ok().put("list", list);
    }


    /**
     * 列表
     */
    @SysLog
    @RequestMapping("/list")
    @RequiresPermissions("op:group:list")
    public R list(@RequestParam Map<String, Object> params){
        String ownerDeptStr = getUserOwnerDept();
        String[] ownerDept = null;
        String dtId = (String) params.get("dtId");
        // 如果选择了机构，查询指定机构的数据
        if(!StringUtils.equals(dtId,getUserDtId().toString())){
            ownerDept = new String[1];
            ownerDept[0] = dtId;
        }else {
            ownerDept = ownerDeptStr.split("\\,");
        }
        params.put("ownerDept",ownerDept);
        PageUtils page = groupService.sqlQueryPage(params);
        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @SysLog
    @RequestMapping("/info/{id}")
    @RequiresPermissions("op:group:info")
    public R info(@PathVariable("id") Integer id){
		GroupEntity group = groupService.getById(id);

        return R.ok().put("group", group);
    }

    /**
     * 保存
     */
    @SysLog
    @RequestMapping("/save")
    @RequiresPermissions("op:group:save")
    @Transactional
    public R save(@RequestBody GroupDto groupDto) {
        R r = groupService.save(groupDto);
        if((int)r.get("code") == 0){
            List<HtlGroupEntity> list = (List<HtlGroupEntity>) r.remove("htl");
            List<DtUpHtlEntity> dtUpHtlEntities = (List<DtUpHtlEntity>) r.remove("dthtl");
            dtUpHtlService.saveOrUpdateBatch(dtUpHtlEntities);
            groupService.saveHtlGroup(list);
        }
        return r;
    }

    /**
     * 保存
     */
    @SysLog
    @RequestMapping("/savesingle")
    @RequiresPermissions("op:group:save")
    public R saveSingle(@RequestBody GroupEntity groupEntity) {
        groupService.updateById(groupEntity);
        return R.ok("修改成功");
    }


    /**
     * 修改
     */
    @SysLog
    @RequestMapping("/update")
    @RequiresPermissions("op:group:update")
    public R update(@RequestBody GroupEntity group){
		groupService.updateById(group);

        return R.ok();
    }

    /**
     * 删除
     */
    @SysLog
    @RequestMapping("/delete/{id}")
    @RequiresPermissions("op:group:delete")
    public R delete(@PathVariable("id")  Integer id){

       Long count =  htlGroupService.sqlQueryByGroupId(id);
       if(count >0){
           return  R.ok("请先删除分组下的酒店");
       }
        groupService.removeById(id);
        return R.ok("删除成功");
    }


    /**
     * 拉取并推送更新分组下的酒店
     */
    @RequestMapping("/pullandpush")
    @RequiresPermissions("op:group:pullandpush")
    public R pullandpush(@RequestParam Map<String, Object> params) {
        Integer storeId = Integer.valueOf(params.get("storId").toString());
        Integer groupId = Integer.valueOf(params.get("groupId").toString());
        boolean result = htlGroupService.hotelInit(groupId, storeId, "xc_hotel_id_list");
        if (!result) {
            return R.error("redis服务异常");
        }
        HtlGroupDto htlGroupDto = new HtlGroupDto();
        htlGroupDto.setStoreId(storeId);
        htlGroupDto.setGroupId(groupId);
        hotelToMQService.pullSendGroup(htlGroupDto);
        return R.ok("开始拉取推送分组下的酒店...");
    }

    /**
     * 开启订单直连
     * @return
     */
    @RequestMapping("direct/start")
    public R directStart(@RequestParam Map<String, Object> params) {
        int flag = 1;
        boolean result = directHandel(params, flag);
        if(result) {
            return R.ok("订单直连开启");
        }
        return R.error("操作失败");
    }

    /**
     * 关闭订单直连
     * @return
     */
    @RequestMapping("direct/stop")
    public R directStop(@RequestParam Map<String, Object> params) {
        int flag = 0;
        boolean result = directHandel(params, flag);
        if(result) {
            return R.ok("订单直连关闭");
        }
        return R.error("操作失败");
    }

    @Transactional
    boolean directHandel(Map<String, Object> params, Integer flag) {
        try {
            Integer groupId = Integer.valueOf((String)params.get("groupId"));
            Integer storeId = Integer.valueOf((String)params.get("storeId"));
            List<Long> list = htlGroupService.getHtlIdsByGroupId(groupId);
            List<DtUpHtlEntity> dtUpHtlEntities = new ArrayList<>();

            for (Long hotelId:list) {
                DtUpHtlEntity dtUpHtlEntity = new DtUpHtlEntity();
                dtUpHtlEntity.setId(Long.valueOf(hotelId.toString() + storeId));
                dtUpHtlEntity.setIsAuto(flag);
                dtUpHtlEntities.add(dtUpHtlEntity);
            }
            dtUpHtlService.updateBatchById(dtUpHtlEntities);
            GroupEntity groupEntity = new GroupEntity();
            groupEntity.setId(groupId);
            groupEntity.setIsDirect(flag);
            groupService.updateById(groupEntity);
        } catch (Exception e) {
            return false;
        }
        return true;
    }
}
